package com.example.studyllm.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wk
 */
public class DatabaseTools {

    public Map<String, Object> executeQuery(DbQueryParams queryParams) throws SQLException {
        String url = queryParams.getUrl();
        String user = queryParams.getUser();
        String password = queryParams.getPassword();
        String query = queryParams.getQuery();
        Object[] params = queryParams.getParams();

        Connection connection = null ;
        try{
            connection = DriverManager.getConnection(url, user, password);
            PreparedStatement preparedStatement = connection.prepareStatement(query);

            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            ResultSet resultSet = preparedStatement.executeQuery();
            Map<String, Object> resultMap = new HashMap<>();

            while (resultSet.next()) {
                for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                    resultMap.put(resultSet.getMetaData().getColumnName(i), resultSet.getObject(i));
                }
            }
            return resultMap;
        }finally {
            closeConnection(connection);
        }
    }

    public int executeUpdate(DbQueryParams queryParams) throws SQLException {
        String url = queryParams.getUrl();
        String user = queryParams.getUser();
        String password = queryParams.getPassword();
        String query = queryParams.getQuery();
        Object[] params = queryParams.getParams();
        Connection connection = null ;
        try{
            connection = DriverManager.getConnection(url, user, password);
            PreparedStatement preparedStatement = connection.prepareStatement(query);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }

            return preparedStatement.executeUpdate();
        }finally {
            closeConnection(connection);
        }
    }

    public void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
